import { Button } from '@/components';
import BaseComponent from '@/components/BaseComponent';
// import Form from '@/components/Form';
// import FormItem from '@/components/Form/item';
import { Form, Input, Popconfirm, Popover } from 'antd';
import React from 'react';
import { Link } from 'umi';

const FormItem = Form.Item;

export default class ConfirmWrap extends BaseComponent {
  state = {
    visible: false,
  };
  hide = () => {
    this.setState({
      visible: false,
    });
  };
  handleVisibleChange = (visible) => {
    this.setState({ visible });
  };

  render() {
    const {
      title,
      confirmText,
      children,
      loadingAble = true,
      ...props
    } = this.props;
    let child = React.Children.only(children);
    if (title || confirmText) {
      let childView = child;
      const { onClick } = child.props;
      let _onClick = () => {
        this.loading = onClick();
        this.setState({});
      };
      // 链接类型跳转特殊处理
      if (child.type == Link) {
        _onClick = (e) => {
          if (child.props.to) {
            Link.goTo(child.props.to);
          }
        };
      } else {
        let conf = {
          onClick: (e) => {
            e.preventDefault();
          },
        };
        if (loadingAble) {
          conf.loading = this.loading;
        }
        childView = React.cloneElement(child, conf);
      }
      if (confirmText) {
        let con = (
          <Form
            onFinish={() => {
              this.hide();
              _onClick();
            }}
          >
            <FormItem
              name="ipt"
              hideVerticalSpace
              validator={({ value }) => {
                if (value == confirmText) {
                  return Promise.resolve('');
                } else {
                  return Promise.reject('');
                }
              }}
            >
              <Input className="w-full" />
            </FormItem>
            <div className="text-right m-t-xs">
              <Button size="small" onClick={this.hide}>
                取消
              </Button>
              <Button
                size="small"
                htmlType="submit"
                className="m-l-xs"
                type="primary"
              >
                确认
              </Button>
            </div>
          </Form>
        );
        return (
          <Popover
            content={con}
            onOpenChange={this.handleVisibleChange}
            open={this.state.visible}
            trigger="click"
            title={`请输入：${confirmText}`}
            {...props}
          >
            {childView}
          </Popover>
        );
      }

      return (
        <Popconfirm
          title={title}
          onConfirm={_onClick}
          {...props}
          okText="确定"
          cancelText="取消"
        >
          {childView}
        </Popconfirm>
      );
    }
    return children;
  }
}
